if [ -d "$HOME/.nvm" ]; then
	echo "NVM already installed in $HOME/.nvm"
	exit
fi

export NVM_DIR="$HOME/.nvm"

git clone https://gitee.com/czyczk/nvm.git "$NVM_DIR"
[ $? -eq 0 ] && cd $HOME/.nvm || exit $?
cd $HOME/.nvm
git checkout `git describe --abbrev=0 --tags --match "v[0-9]*" $(git rev-list --tags --max-count=1)`

if [[ $SHELL == */zsh ]]; then
	echo "#NVM (defer init + Zsh ver.)
# Defer initialization of nvm until nvm, node or a node-dependent command is
# run. Ensure this block is only run once if .zshrc gets sourced multiple times
# by checking whether __init_nvm is a function.
if [ -s \"\$HOME/.nvm/nvm.sh\" ] && [ ! \"\$(whence -w __init_nvm)\" = function ]; then
  export NVM_DIR=\"\$HOME/.nvm\"
  [ -s \"\$NVM_DIR/bash_completion\" ] && . \"\$NVM_DIR/bash_completion\"
  declare -a __node_commands=('nvm' 'node' 'npm' 'yarn' 'gulp' 'grunt' 'webpack')
  function __init_nvm() {
    for i in \"\${__node_commands[@]}\"; do unalias \$i; done
    . \"\$NVM_DIR\"/nvm.sh
    unset __node_commands
    unset -f __init_nvm
  }
  for i in \"\${__node_commands[@]}\"; do alias \$i='__init_nvm && '\$i; done
fi" >> $HOME/.zshrc
elif [[ $SHELL == */bash ]]; then
	echo "# NVM (defer init + Bash ver.)
# Defer initialization of nvm until nvm, node or a node-dependent command is
# run. Ensure this block is only run once if .bashrc gets sourced multiple times
# by checking whether __init_nvm is a function.
if [ -s \"\$HOME/.nvm/nvm.sh\" ] && [ ! \"\$(type -t __init_nvm)\" = function ]; then
  export NVM_DIR=\"\$HOME/.nvm\"
  [ -s \"\$NVM_DIR/bash_completion\" ] && . \"\$NVM_DIR/bash_completion\"
  declare -a __node_commands=('nvm' 'node' 'npm' 'yarn' 'gulp' 'grunt' 'webpack')
  function __init_nvm() {
    for i in \"\${__node_commands[@]}\"; do unalias \$i; done
    . \"\$NVM_DIR\"/nvm.sh
    unset __node_commands
    unset -f __init_nvm
  }
  for i in \"\${__node_commands[@]}\"; do alias \$i='__init_nvm && '\$i; done
fi" >> $HOME/.bashrc
else
	echo "No supported environment configurations for this shell. Please do configurations yourself."
	exit 2
fi

echo "NVM will be available in new opened shells."

